#include<stdio.h>
#include<netinet/in.h>
#include<string.h>
#include<mysql.h>

int main()
{
	int fd = 0;
	fd = socket(AF_INET,SOCK_DGRAM,0);
	if(fd<0){
		perror("socket");
	}
	struct sockaddr_in dst;
	dst.sin_family = AF_INET;
	dst.sin_port = htons(12204);
	dst.sin_addr.s_addr = INADDR_ANY;

	int ret = 0;
	ret = bind(fd,&dst,16);
	if(ret<0){
		 perror("bind");
	}

	MYSQL tmp;
	MYSQL *my = NULL;
	my = mysql_init(&tmp);
	int *r = NULL;
	r = mysql_real_connect(my,"localhost","root","MzYj@123456","nbiot",0,NULL,0);
	if(r == NULL){
		printf("mysql real connect error\n");
		return 1;
	}
	while(1){
		char data[1024] = {0};
		struct sockaddr_in send;
		int send_len = 0;
		ret = recvfrom(fd,data,1024,0,&send,&send_len);
		if(ret<0){
			perror("recvfrom");
		}
		char *c=data;
		char d[20];
		memcpy(d, c+27, 20);
		d[20]='\0';
		printf("%s", d);
		printf("\n");
		char *a = d;
		char *delete = "delete from nbiot";
		char *b = "INSERT INTO nbiot(number,data)values(1,";
		char query[255];
		sprintf(query,"%s%s%s%s",b,"\"",a,"\""")");
		printf(query);
		printf("\n");
		int del = mysql_query(my, delete);
		if(del != 0){
			perror("delete error!\n");	
		}
		int ins = mysql_query(my, query);
		if(ins != 0){
			perror("query error!\n");
		}
	}	
}
